#include "threadPool.h"


int threadPoolInit(threadPool_t *pthreadPool, int workerNum) {
   if(!pthreadPool || workerNum <= 0) {
      LOG(LOG_LEVEL_ERROR, "system", "threadPoolInit: Invalid parameters: pthreadPool=%p, workerNum=%d",
          pthreadPool, workerNum);
      return -1; // 参数错误
   }



   taskQueueInit(&pthreadPool->taskQueue);
   tidArrInit(&pthreadPool->tidArr, workerNum);

   if(pthread_mutex_init(&pthreadPool->mutex, NULL) != 0) {
      LOG(LOG_LEVEL_ERROR, "system", "threadPoolInit: Failed to initialize mutex");
      return -1; // 锁初始化失败
   }

   if(pthread_mutex_init(&pthreadPool->sqlmutex,NULL)!=0){
      LOG(LOG_LEVEL_ERROR, "system", "threadPoolInit: Failed to initialize sqlmutex");
      return -1; // 锁初始化失败
   }

   if(pthread_cond_init(&pthreadPool->cond, NULL) != 0) {
      LOG(LOG_LEVEL_ERROR, "system", "threadPoolInit: Failed to initialize condition variable");
      pthread_mutex_destroy(&pthreadPool->mutex);
      return -1; // 条件变量初始化失败
   }

   //失败原因，结构体初始化之前未分配空间，pool在main函数中就分配了
   //但是pthreadContext在threadPoolInit中没有分配空间
   pthreadPool->pthreadContext = (threadContext_t *)malloc(sizeof(threadContext_t) * workerNum);
   if(pthreadPool->pthreadContext == NULL) {
      LOG(LOG_LEVEL_ERROR, "system", "threadPoolInit: Failed to allocate memory for pthreadContext");
      pthread_mutex_destroy(&pthreadPool->mutex);
      pthread_cond_destroy(&pthreadPool->cond);
      return -1; // 内存分配失败
   }
   for(int i = 0; i < workerNum; i++) {
      pthreadPool->pthreadContext[i].threadID = i;
      pthreadPool->pthreadContext[i].pthreadPool = pthreadPool;
      pthreadPool->pthreadContext[i].pstack = (pathStack_t *)malloc(sizeof(pathStack_t));
      //stackInit(pthreadPool->pthreadContext[i].pstack);
      pthreadPool->pthreadContext[i].pthreadFileMeta = (fileMetaData_t *)malloc(sizeof(fileMetaData_t));
      pthreadPool->pthreadContext[i].pthreadMysql = NULL;
      //注意堆分配后必须释放
      //释放放在了main函数中
      //线程堆内存生命周期是进程级
   }

    pthreadPool->exitFlag = 0;
   return 0;
}